package ru.minidoc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import ru.minidoc.model.Project;

public class ProjectDao extends AbstractDao {
    public int create(Project project) {
        return queryAndReturnIdentity(
                "insert into project(name, assignedTo, modified) values(?,?,now());",
                new Object[] { project.getName(), project.getAssignedToId() });
    }

    public void delete(Project project) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update(
                "delete from project where id = ?",
                new Object[] { project.getId() });
    }

    public List<Project> getProjectList() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        List<Project> result = jdbcTemplate.query(
                "select project.id, project.name, project.assignedTo,"
                + " project.modified, user.fullname from project"
                + " left join user on user.id = project.assignedTo",
                new RowMapper<Project>() {

                    @Override
                    public Project mapRow(ResultSet rs, int rowNum)
                            throws SQLException {
                        Project project = new Project();
                        project.setId(rs.getInt(1));
                        project.setName(rs.getString(2));
                        project.setAssignedToId(rs.getInt(3));
                        project.setModified(rs.getString(4));
                        project.setAssignedTo(rs.getString(5));
                        return project;
                    }
                });
        return result;
    }

    public void update(Project project) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.update(
                "update project set name = ?, assignedTo=?, modified=now() where id = ?",
                new Object[] {project.getName(), project.getAssignedToId(), project.getId()});
    }
}
